<template>
  <div class="chat-container">
    <toast-message ref="toast" />
    <div class="header">
      <!-- API Key验证区域 -->
      <api-key-verifier />
      <div class="header-actions">
        <el-tooltip
          content="清空聊天记录"
          placement="top"
        >
          <el-button
            type="primary"
            :icon="Delete"
            @click="clearMessages"
          />
        </el-tooltip>
      </div>
    </div>

    <div class="messages">
      <div
        v-for="(msg, index) in messages"
        :key="index"
        :class="['message', msg.isUser ? 'user' : 'assistant']"
        @mouseover="showActions[index] = true"
        @mouseleave="showActions[index] = false"
      >
        <template v-if="msg.type === 'text'">
          <div class="message-content">
              <pre v-if="!msg.isExpanded && msg.content.length > 500" class="message-text">{{ msg.content.slice(0, 500)
                }}...<el-button link type="primary" @click="msg.isExpanded = true">查看更多</el-button></pre>
            <pre v-else class="message-text">{{ msg.content }}<el-button v-if="msg.content.length > 500" link
                                                                         type="primary"
                                                                         @click="msg.isExpanded = false">收起</el-button></pre>
            <div v-show="showActions[index]" class="message-actions">
              <el-button-group>
                <el-button
                  v-if="msg.isUser"
                  :icon="Edit"
                  @click="editMessage(index)"
                />
                <el-button
                  :icon="DocumentCopy"
                  @click="copyMessage(msg.content)"
                />
                <el-button
                  :icon="Delete"
                  @click="deleteMessage(index)"
                />
              </el-button-group>
            </div>
          </div>
        </template>
        <template v-else-if="msg.type === 'image'">
          <img
            :src="'data:image/png;base64,' + msg.content"
            class="generated-image"
          />
        </template>
      </div>
    </div>

    <div class="input-area">
      <el-input
        v-model="inputText"
        placeholder="输入提示词..."
        :disabled="generating"
        @keyup.enter="handleSend"
        @input="handleInput"
      >
      </el-input>
      <div v-if="isTyping" class="typing-indicator">正在输入...</div>
      <el-button
        type="primary"
        @click="handleSend"
        :loading="generating"
        :disabled="generating || !selectedModel"
      >
        发送
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Delete, DocumentCopy, Edit } from '@element-plus/icons-vue'
import { chatApi, type Message } from '@/services/chat'
import ToastMessage from './ToastMessage.vue'
import ApiKeyVerifier from './ApiKeyVerifier.vue'
import '@/styles/chat.scss'
import { useApiKeyStore } from '@/stores/apiKeyStore.ts'

// 使用全局API Key store
const apiKeyStore = useApiKeyStore()

// 提取store中的状态
const isKeyVerified = computed(() => apiKeyStore.isKeyVerified)
const selectedModel = computed(() => apiKeyStore.selectedModel)

const props = defineProps<{
  messages: Array<Message>
  generating: boolean
  sdServiceAvailable: boolean
}>()

const emit = defineEmits<{
  (e: 'send', data: { text: string; model: string }): void
  (e: 'toggle-batch'): void
  (e: 'clear'): void
  (e: 'verify-key', key: string): void
}>()

const inputText = ref('')
const typingTimeout = ref<number | null>(null)
const isTyping = ref(false)
const apiKeyVerifier = ref<InstanceType<typeof ApiKeyVerifier> | null>(null)

// 初始化加载配置和历史记录
onMounted(async () => {
  try {
    // 确保API Key验证已经完成，避免重复初始化
    if (!apiKeyStore.hasInitialized && !apiKeyStore.isKeyVerified) {
      console.log('ChatPanel组件初始化API Key')
      await apiKeyStore.initialize()
    }

    // 获取历史记录
    const historyResponse = await chatApi.getHistory()
    if (historyResponse.data?.success && historyResponse.data?.history) {
      const formattedMessages = historyResponse.data.history.map((item: {
        role: string
        content: string
      }) => ({
        type: 'text' as const,
        content: item.content,
        isUser: item.role === 'user'
      }))
      props.messages.push(...formattedMessages)
    }
  } catch (error) {
    console.error('初始化失败:', error)
    toast.value?.show('加载配置或历史记录失败', 5000)
  }
})

const toast = ref<InstanceType<typeof ToastMessage> | null>(null)
const showActions = ref<{ [key: number]: boolean }>({})
const editingIndex = ref<number | null>(null)

const handleInput = () => {
  if (typingTimeout.value) {
    clearTimeout(typingTimeout.value)
  }
  isTyping.value = true
  typingTimeout.value = window.setTimeout(() => {
    isTyping.value = false
  }, 1000)
}

const handleSend = () => {
  // 确保API Key已验证
  if (!isKeyVerified.value) {
    toast.value?.show('请先验证API Key', 2000)
    return
  }
  if (!inputText.value.trim() || !selectedModel.value) {
    toast.value?.show('不能发送空消息！', 2000)
    return
  }
  if (editingIndex.value !== null) {
    props.messages[editingIndex.value].content = inputText.value
    editingIndex.value = null
  } else {
    emit('send', { text: inputText.value, model: selectedModel.value })
  }
  inputText.value = ''
  isTyping.value = false
  if (typingTimeout.value) {
    clearTimeout(typingTimeout.value)
  }
}
const copyMessage = (content: string) => {
  navigator.clipboard.writeText(content)
  toast.value?.show('已复制到剪贴板', 2000)
}

const editMessage = (index: number) => {
  const message = props.messages[index]
  if (message.isUser) {
    inputText.value = message.content
    editingIndex.value = index
  }
}

const deleteMessage = async (index: number) => {
  try {
    await chatApi.deleteMessage(index)
    props.messages.splice(index, 1)
    toast.value?.show('消息已删除', 2000)
  } catch (error) {
    console.error('删除消息失败:', error)
    toast.value?.show('删除消息失败', 3000)
  }
}

const clearMessages = () => {
  emit('clear')
}
</script>

<style scoped>
.chat-container {
  background: white;
  border-radius: var(--border-radius);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  height: 80vh;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  margin-bottom: 1rem;
  border: 1px solid #ebeef5;
  border-radius: var(--border-radius);
  display: flex;
  flex-direction: column;
  gap: 1rem;
  min-height: 0;
  box-sizing: border-box;
}

/* 输入框区域固定高度 */
.input-box {
  height: 60px;
  border-top: 1px solid #ebeef5;
  padding: 0.5rem;
  display: flex;
  align-items: center;
  box-sizing: border-box;
}

.input-area {
  position: relative;
  flex-shrink: 0;
  height: 60px;
  min-height: 60px;
  padding-top: 1rem;
  display: flex;
  gap: 1rem;
  align-items: center;
}

.input-area .el-input {
  flex: 1;
}

.input-area .el-input__inner {
  height: 40px;
}

.key-verify-area {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  align-items: center;
}

.message-content {
  position: relative;
  width: 100%;
}

.message-text {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  line-height: 1.5;
  padding: 0.5rem;
}

.message {
  margin: 0;
  padding: 0.25rem 0.5rem;
  border-radius: var(--border-radius);
  position: relative;
  max-width: 85%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.message-actions {
  position: absolute;
  top: 0;
  right: 0;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: var(--border-radius);
  padding: 0.15rem;
  opacity: 0;
  transition: opacity 0.2s;
}

.message:hover .message-actions {
  opacity: 1;
}

.message.user {
  background-color: #ecf5ff;
  margin-left: auto;
}

.message.assistant {
  background-color: #f5f7fa;
  margin-right: auto;
}

.message .el-button--link {
  padding: 0;
  margin-left: 0.5rem;
  font-size: 0.9rem;
}

.message-actions {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: var(--border-radius);
  padding: 0.25rem;
}

.generated-image {
  max-width: 100%;
  border-radius: var(--border-radius);
  margin: 0.5rem 0;
}

/* 删除重复的input-area样式 */

.model-info {
  margin-top: 1rem;
  color: var(--text-color);
  font-size: 0.9rem;
  text-align: right;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.header-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.typing-indicator {
  position: absolute;
  bottom: 100%;
  left: 0;
  font-size: 0.8rem;
  color: #909399;
  margin-bottom: 0.5rem;
}
</style>
